package com.example.demo.services;

import java.util.ArrayList;
import java.util.Date;

import org.springframework.stereotype.Service;

import com.example.demo.dto.UserDto;

@Service
public class UserDaoService {
    public static int userCount = 5;
    private static ArrayList<UserDto> users = new ArrayList<>();
    static {
        // adding users to the list
        users.add(new UserDto(1, "John", new Date()));
        users.add(new UserDto(2, "Robert", new Date()));
        users.add(new UserDto(3, "Adam", new Date()));
        users.add(new UserDto(4, "Andrew", new Date()));
        users.add(new UserDto(5, "Jack", new Date()));
    }

    public ArrayList<UserDto> findAll() {
        return users;
    }

    public UserDto save(UserDto user) {
        if (user.getId() == null) {
            user.setId(++userCount);
            user.setDob(new Date());
        }
        users.add(user);
        return user;
    }

    public UserDto findOne(int id) {
        for (UserDto userDto : users) {
            if (userDto.getId() == id) {
                return userDto;
            }
        }
        return null;
    }

    public void deleteById(int id) {
        for (UserDto userDto : users) {
            if (userDto.getId() == id) {
                users.remove(userDto);
            }
        }
    }
}
